﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}

<link href="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/css/layui.min.css" rel="stylesheet">
<!-- 如有自定义CSS文件，确保路径和文件存在，否则可删除下一行 -->
<!-- <link href="~/wwwroot/libs/shiftschedulecalendar.css" rel="stylesheet"> -->
<!-- 先引入jQuery，再引入layui -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/layui.min.js"></script>

<div class="layui-tab" lay-filter="mainTab">
  <ul class="layui-tab-title">
    <li class="layui-this">选择设备类型</li>
    <li id="teamTabTitle">选择班组与排班</li>
  </ul>
  <div class="layui-tab-content" style="padding:0;">
    <div class="layui-tab-item layui-show">
      <!-- 设备类型选择，样式与班组tab一致 -->
      <main class="main-container">
        <aside class="sidebar">
          <h3>设备类型</h3>
          <div style="position:relative;">
            <input type="text" id="equipmentTypeSearch" placeholder="搜索设备类型" class="layui-input" style="margin-bottom:5px;">
            <button class="clear-btn" id="clearEquipmentTypeSearch" aria-label="清除">×</button>
          </div>
          <ul id="equipmentTypeList" style="max-height:200px;overflow:auto;"></ul>
        </aside>
      </main>
    </div>
    <div class="layui-tab-item">
      <!-- 班组选择与排班日历 -->
      <main class="main-container">
        <aside class="sidebar">
          <h3>班组</h3>
          <div style="position:relative;">
            <input type="text" id="teamSearch" placeholder="搜索班组" class="layui-input" style="margin-bottom:5px;">
            <button class="clear-btn" id="clearTeamSearch" aria-label="清除">×</button>
          </div>
          <ul id="teamList" style="max-height:200px;overflow:auto;"></ul>
        </aside>
        <section id="calendarContainer" aria-label="班表日历">
          <div id="calendarLoading"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop" style="font-size:36px;"></i></div>
        </section>
      </main>
      <nav class="calendar-toolbar" aria-label="日历工具栏">
        <button class="layui-btn layui-btn-primary" id="prevMonth" aria-label="上个月">上个月</button>
        <button class="layui-btn layui-btn-normal" id="today" aria-label="今天">今天</button>
        <button class="layui-btn layui-btn-primary" id="nextMonth" aria-label="下个月">下个月</button>
        <span id="calendarTitle" aria-live="polite"></span>
      </nav>
    </div>
  </div>
</div>

<script>
layui.use(['element', 'layer', 'form'], function(){
    const element = layui.element, layer = layui.layer, form = layui.form;
    let current = new Date();
    let shiftData = {};
    let selectedEquipmentType = null;
    let selectedEquipmentTypeCode = null;
    let selectedTeam = null;
    let selectedTeamNumber = null;

    // tab切换控制
    function setTeamTabEnabled(enabled) {
        const $tab = $('#teamTabTitle');
        if(enabled) {
            $tab.removeClass('layui-disabled');
        } else {
            $tab.addClass('layui-disabled');
        }
    }

    // 设备类型选中后自动切换到班组tab
    $(document).on('click', '.equipment-type-item', function() {
        $('.equipment-type-item').removeClass('selected');
        $(this).addClass('selected');
        selectedEquipmentType = $(this).data('id');
        selectedEquipmentTypeCode = $(this).data('code');
        localStorage.setItem('lastEquipmentTypeCode', selectedEquipmentTypeCode || '');
        setTeamTabEnabled(true);
        element.tabChange('mainTab', 1);
        refreshCalendar();
    });

    // 禁用班组tab时阻止切换
    $(document).on('click', '#teamTabTitle.layui-disabled', function(e){
        e.preventDefault();
        layer.msg('请先选择设备类型');
        return false;
    });

    // 页面加载时禁用班组tab
    $(function(){
        setTeamTabEnabled(!!localStorage.getItem('lastEquipmentTypeCode'));
    });

    function setLoading(isLoading) {
        if(isLoading) {
            $('#calendarContainer').addClass('loading');
            $('#calendarLoading').show();
        } else {
            $('#calendarContainer').removeClass('loading');
            $('#calendarLoading').hide();
        }
    }

    // 拉取排班数据
    function loadShiftData(year, month, callback) {
        if (!selectedEquipmentType || !selectedTeam) {
            shiftData = {};
            callback && callback();
            return;
        }
        setLoading(true);
        $.post('/Workforcemanagement/GetShiftData', {
            year: year,
            month: month + 1,
            equipmentTypeCode: selectedEquipmentTypeCode,
            teamNumber: selectedTeamNumber,
            __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
        }, function(res) {
            shiftData = {};
            (res.data || []).forEach(item => {
                const dateKey = (item.date || '').slice(0, 10);
                shiftData[dateKey] = item;
            });
            setLoading(false);
            callback && callback();
        });
    }

    // 渲染日历
    function renderCalendar(date) {
        if (!selectedEquipmentType || !selectedTeam) {
            $('#calendarContainer').css('opacity', 0.5).html('<div class="empty-tip">请先选择设备类型和班组</div>');
            return;
        }
        $('#calendarContainer').css('opacity', 1);
        // 无论有无数据都渲染日历表格
        $('#calendarContainer').html(generateCalendarHtml(date));
        $('#calendarTitle').text(`${date.getFullYear()}年${date.getMonth()+1}月`);
    }

    function refreshCalendar() {
        if (!selectedEquipmentType || !selectedTeam) {
            renderCalendar(current);
            return;
        }
        setLoading(true);
        loadShiftData(current.getFullYear(), current.getMonth(), function() {
            setLoading(false);
            renderCalendar(current);
        });
    }

    function generateCalendarHtml(date) {
        const year = date.getFullYear(), month = date.getMonth();
        const firstDay = new Date(year, month, 1);
        const lastDay = new Date(year, month+1, 0);
        const startDay = firstDay.getDay();
        const days = lastDay.getDate();
        let html = '<table class="layui-table" aria-label="排班日历"><thead><tr>';
        const week = ['日','一','二','三','四','五','六'];
        week.forEach(day => html += `<th>${day}</th>`);
        html += '</tr></thead><tbody><tr>';
        for(let i=0;i<startDay;i++) html += '<td></td>';
        for(let d=1;d<=days;d++){
            const day = new Date(year, month, d);
            const dateStr = day.toISOString().slice(0,10);
            let cellContent = `${d}<div class="shift-label">班</div>`;
            if(shiftData[dateStr]) {
                let shiftClass = '';
                if(shiftData[dateStr].shift === '早班') shiftClass = 'shift-morning';
                else if(shiftData[dateStr].shift === '中班') shiftClass = 'shift-afternoon';
                else if(shiftData[dateStr].shift === '晚班') shiftClass = 'shift-night';
                cellContent += `<div class="shift-info ${shiftClass}">
                    <span>${shiftData[dateStr].shift}</span> -
                    <span>${shiftData[dateStr].person}</span>
                    <div class="tooltip">设备类型: ${$('#equipmentTypeList .selected').text() || ''}<br>班组: ${$('#teamList .selected').text() || ''}</div>
                </div>`;
            } else {
                cellContent += `<div class="shift-info shift-empty">无排班</div>`;
            }
            html += `<td class="calendar-cell" tabindex="0" data-date="${dateStr}">${cellContent}</td>`;
            if((startDay+d)%7==0) html += '</tr><tr>';
        }
        html += '</tr></tbody></table>';
        return html;
    }

    // 月份切换
    $('#prevMonth').click(()=>{ current.setMonth(current.getMonth()-1); refreshCalendar(); });
    $('#nextMonth').click(()=>{ current.setMonth(current.getMonth()+1); refreshCalendar(); });
    $('#today').click(()=>{ current = new Date(); refreshCalendar(); });

    // 加载设备类型
    function loadEquipmentTypes() {
        $.post('/Workforcemanagement/GetEquipmentType', {
            __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
            pageIndex: 1,
            pageSize: 100
        }, function(res) {
            let html = (res.data || []).map(e =>
                `<li class="equipment-type-item" data-id="${e.id}" data-code="${e.equipmentTypeCode}">${e.equipmentTypeName}</li>`
            ).join('');
            if(!html) html = '<li style="color:#aaa;">暂无设备类型</li>';
            $('#equipmentTypeList').html(html);
        });
    }

    // 加载班组
    function loadTeams() {
        $.post('/Workforcemanagement/QueryTeam', {
            __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
            page: 1,
            limit: 100,
            TeamNumber: '',
            TeamName: '',
            TeamType: ''
        }, function(res) {
            let html = (res.data || []).map(t =>
                `<li class="team-item" data-id="${t.id}" data-code="${t.teamNumber}">${t.teamName}</li>`
            ).join('');
            if(!html) html = '<li style="color:#aaa;">暂无班组</li>';
            $('#teamList').html(html);
        });
    }

    // 选中班组
    $(document).on('click', '.team-item', function() {
        $('.team-item').removeClass('selected');
        $(this).addClass('selected');
        selectedTeam = $(this).data('id');
        selectedTeamNumber = $(this).data('code');
        localStorage.setItem('lastTeamNumber', selectedTeamNumber || '');
        refreshCalendar();
    });

    // 点击日历单元格排班
    $(document).on('click keypress', '.calendar-cell', function(e){
        if(e.type === 'click' || e.key === 'Enter'){
            const date = $(this).data('date');
            if(!selectedEquipmentType || !selectedTeam){
                layer.msg('请先选择设备类型和班组');
                return;
            }
            layer.open({
                type: 1,
                title: `${date} 排班`,
                area: ['400px', '300px'],
                content: `<form class="layui-form" style="margin:20px;">
                    <div class="layui-form-item"><label class="layui-form-label">班次</label>
                        <div class="layui-input-block">
                            <select name="shift" required>
                                <option value="">请选择</option>
                                <option value="早班">早班</option>
                                <option value="中班">中班</option>
                                <option value="晚班">晚班</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item"><label class="layui-form-label">人员</label>
                        <div class="layui-input-block">
                            <input type="text" name="person" required placeholder="输入人员" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item"><label class="layui-form-label">设备类型编码</label>
                        <div class="layui-input-block">
                            <input type="text" name="equipmentTypeCode" value="${selectedEquipmentTypeCode || ''}" placeholder="设备类型编码" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item"><label class="layui-form-label">设备类型名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="equipmentTypeName" value="${$('#equipmentTypeList .selected').text() || ''}" placeholder="设备类型名称" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item"><label class="layui-form-label">班组编号</label>
                        <div class="layui-input-block">
                            <input type="text" name="teamNumber" value="${selectedTeamNumber || ''}" placeholder="班组编号" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item"><label class="layui-form-label">班组名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="teamName" value="${$('#teamList .selected').text() || ''}" placeholder="班组名称" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item"><label class="layui-form-label">备注</label>
                        <div class="layui-input-block">
                            <input type="text" name="remark" placeholder="输入备注" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button class="layui-btn" lay-submit lay-filter="saveShift">保存</button>
                        </div>
                    </div>
                </form>`,
                success: function(layero, index){
                    form.render();
                    form.on('submit(saveShift)', function(data){
                        if(!data.field.person){
                            layer.msg('人员不能为空');
                            return false;
                        }
                        const postData = {
                            date: date,
                            shift: data.field.shift,
                            person: data.field.person,
                            equipmentTypeCode: data.field.equipmentTypeCode || selectedEquipmentTypeCode,
                            equipmentTypeName: data.field.equipmentTypeName || $('#equipmentTypeList .selected').text() || '',
                            teamNumber: data.field.teamNumber || selectedTeamNumber,
                            teamName: data.field.teamName || $('#teamList .selected').text() || '',
                            remark: data.field.remark || ''
                        };
                        $.ajax({
                            url: '/Workforcemanagement/SaveShift',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify(postData),
                            headers: {
                                'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                            },
                            success: function(res){
                                layer.msg('排班已保存');
                                layer.close(index);
                                refreshCalendar();
                            },
                            error: function(){
                                layer.msg('保存失败，请重试');
                            }
                        });
                        return false;
                    });
                }
            });
        }
    });

    // 搜索过滤和清除按钮
    $('#equipmentTypeSearch').on('input', function() {
        let val = $(this).val().toLowerCase();
        $('#equipmentTypeList li').each(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(val) > -1);
        });
    });
    $('#clearEquipmentTypeSearch').click(function() {
        $('#equipmentTypeSearch').val('').trigger('input');
    });
    $('#teamSearch').on('input', function() {
        let val = $(this).val().toLowerCase();
        $('#teamList li').each(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(val) > -1);
        });
    });
    $('#clearTeamSearch').click(function() {
        $('#teamSearch').val('').trigger('input');
    });

    // 页面加载时拉取数据
    loadEquipmentTypes();
    loadTeams();
    refreshCalendar();

    // 页面加载后自动恢复上次选中的设备类型和班组
    $(document).ready(function() {
        setTimeout(function() {
            const lastEquipmentTypeCode = localStorage.getItem('lastEquipmentTypeCode');
            const lastTeamNumber = localStorage.getItem('lastTeamNumber');
            if (lastEquipmentTypeCode) {
                $('#equipmentTypeList .equipment-type-item').each(function() {
                    if ($(this).data('code') == lastEquipmentTypeCode) {
                        $(this).click();
                    }
                });
            }
            if (lastTeamNumber) {
                $('#teamList .team-item').each(function() {
                    if ($(this).data('code') == lastTeamNumber) {
                        $(this).click();
                    }
                });
            }
        }, 500);
    });
});
</script>

<style>
    .main-container {
        display: flex;
        gap: 40px;
        margin-bottom: 20px;
    }

    .sidebar {
        min-width: 180px;
        background: #fafbfc;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.04);
        padding: 16px 12px;
    }

    #calendarContainer {
        flex: 1;
        min-width: 600px;
        background: #fff;
        border-radius: 10px;
        box-shadow: 0 4px 24px rgba(0,0,0,0.08);
        padding: 20px;
        position: relative;
        transition: opacity 0.3s;
    }

        #calendarContainer.loading {
            opacity: 0.5;
            pointer-events: none;
        }

    #calendarLoading {
        display: none;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        z-index: 20;
    }

    #calendarContainer.loading #calendarLoading {
        display: block;
    }

    .empty-tip {
        text-align: center;
        color: #aaa;
        font-size: 18px;
        margin-top: 60px;
    }

    .clear-btn {
        position: absolute;
        right: 8px;
        top: 8px;
        background: none;
        border: none;
        color: #bbb;
        font-size: 18px;
        cursor: pointer;
        display: none;
    }

    input:focus + .clear-btn, input:not(:placeholder-shown) + .clear-btn {
        display: inline;
    }

    .selected {
        background: #e6f7ff;
        color: #1890ff;
        font-weight: bold;
        transition: background 0.3s;
    }

    .calendar-toolbar {
        margin-bottom: 10px;
    }

    .shift-label {
        background: #409eff;
        color: #fff;
        border-radius: 4px;
        padding: 2px 6px;
        display: inline-block;
        margin-top: 4px;
    }

    .calendar-cell {
        cursor: pointer;
        transition: background 0.2s;
        position: relative;
    }

        .calendar-cell:focus, .calendar-cell:hover {
            background: #f0faff;
            outline: 2px solid #409eff;
        }

    #calendarContainer table {
        width: 100%;
    }

    .shift-info {
        margin-top: 4px;
        font-size: 12px;
    }

    .shift-morning {
        background: #ffe58f;
        color: #ad6800;
    }

    .shift-afternoon {
        background: #ffd6e7;
        color: #c41d7f;
    }

    .shift-night {
        background: #bae7ff;
        color: #0050b3;
    }

    .calendar-cell .tooltip {
        display: none;
        position: absolute;
        left: 0;
        top: 100%;
        background: #fff;
        border: 1px solid #ccc;
        padding: 5px 10px;
        z-index: 10;
        box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        min-width: 120px;
    }

    .calendar-cell:hover .tooltip {
        display: block;
    }

    .shift-empty {
        color: #ccc;
        font-style: italic;
        margin-top: 4px;
    }
</style>

@Html.AntiForgeryToken()
